﻿using System;
using System.Collections.Generic;
using System.Linq;
using TFramework.ECS.Component;
using TFramework.ECS.Entity;
using TFramework.ECS.Group;
using TFramework.ECS.Group.Manager;
using TFramework.ECS.System;

namespace TFramework.Extensions
{
    public static class IEnumerableExtensions
    {
        public static void ForEachRun<T>(this IEnumerable<T> enumerable, Action<T> method)
        {
            foreach (var item in enumerable)
            {
                method(item);
            }
        }

        public static IEnumerable<IEntity> MatchingGroup(this IEnumerable<IEntity> entities, IGroup group)
        { return entities.Where(group.Matches); }

        public static IEnumerable<IEntity> MatchingGroup(this IEnumerable<IEntity> entities, GroupLookup group)
        { return entities.Where(x => group.Matches(x)); }

        public static IEnumerable<ISystem> GetApplicableSystems(this IEnumerable<ISystem> systems, IEntity entity)
        { return systems.Where(x => entity.MatchesGroup(x.Group)); }

        public static IEnumerable<ISystem> GetApplicableSystems(this IEnumerable<ISystem> systems, IEnumerable<IComponent> components)
        {
            var componentTypes = components.Select(x => x.GetType());
            return systems.Where(x => x.Group.RequiredComponents.All(y => componentTypes.Contains(y)));
        }
    }
}